const { createApp } = Vue
createApp({
    created() {
        let self = this;
        //检测版本呢如果版本不一致则强行更新
        localforage.getItem('version', function(err, value) {
            if(value==null || self.version!=value){
                alert("版本不一致,请重新刷新页面！");
                localforage.setItem('version',self.version);
                self.delCache();
            }
        });
        //加载mp3列表
        localforage.keys().then(function(keys) {
            self.exitMp3List = keys;
            self.musicList = musicData;
        });
        localforage.getItem('exitEnglishList', function(err, value) {
            if(value!=null){
                self.exitEnglishList = value;
            }
            self.fetchData();
            localforage.getItem('currPage', function(err, value) {
                self.pageBtn(value-1);
            });
        });
        //启动背景音乐线程检查
        self.checkProgress();
    },
    data() {
        return {
            sourceData:null,
            version:1.2,
            showData:null,
            isShow:false,
            pageNum:1,
            pageSize:50,
            sound:true, //是否开启读音
            musicAudio:null,
            musicList:[],
            isShowMusicDiv:false,
            currMusicItem:true,
            musicMsg:"",
            exitMp3List:[],
            exitEnglishList:[],
            isReview:false
        }
    },
    methods: {
        //进度条
        progressBar(index){
            let self = this;
            if((index+1)>self.showData.length){
                return;
            }
            let item = self.showData[index];

            if(item['isEnd']){
                item.isShow = true;
            }
            var obj = document.getElementById("word_"+item.id);
            obj.classList.add('progress-1');
            obj.addEventListener("webkitAnimationEnd",self.progressEndEvent, obj);
        },
        progressEndEvent(event){
            event.target.classList.remove('progress-1');
            event.target.classList.add('lined');
        },
        //获取地址栏参数
        pageBtn(num){
            let self = this;
            self.pageNum=(self.pageNum+num);
            if(self.pageNum<=0){
                self.pageNum =1;
            }
            localforage.setItem('currPage',self.pageNum);
            self.fetchData();
            //self.showAndHide('all');
            self.isShow=false;
        },
        //复习模式
        reviewBtn(){
            let self = this;
            self.isReview = !self.isReview ;
           /* let isHistory = false;
            if(res==true){
                let isHistory=confirm("确定吗?数据将重新加载");
            }*/
            if(self.isReview){
                let isHistory=confirm("是否继续复习目前的数据?"); //在页面上弹出对话框
                localforage.getItem('currPage',function (err,val) {
                    self.pageNum=1;
                    self.pageSize=self.pageSize*val;
                    if(isHistory){
                        self.fetchHishtoryData();
                    }else{
                        self.fetchData();
                    }
                });
            }else{
                localforage.getItem('currPage',function (err,val) {
                    self.pageNum=val;
                    self.pageSize=50;
                    self.fetchData();
                });
            }
        },
        fetchData() {
            let self = this;
            self.showData = self.returnAllPageFunc(self.pageNum,self.pageSize,englishData);
            if(self.isReview){
                self.showData.forEach(function (item, index) {
                    item['sortValue']= 10+ Math.random() + 0.5;
                    item['isShow']= false;
                });
                self.showData.sort(this.compare('sortValue'));
                localStorage.setItem("historyExitEnglishList",JSON.stringify(self.showData));
            }
            self.dealData();
        },
        fetchHishtoryData(){
            let self = this;
            //获取本地缓存数据 主要用于复习
            var str = localStorage.getItem('historyExitEnglishList');
            if(str==null){
                self.showData = self.returnAllPageFunc(self.pageNum,self.pageSize,englishData);
            }else{
                self.showData =JSON.parse(str);
            }
            self.dealData();
        },
        dealData(){
            let self = this;
            self.showData.forEach(function (item, index) {
                item['isShow']= self.isShow;
                item['progressBar']= 0;
            });
        },
        delCache(){
            let self = this;
            localforage.clear().then(function() {
                window.location.reload();
                console.log('Database is now empty.');
            });
        },
        showAndHide(word){
            let self = this;
            if(word!='all'){//单个隐藏或展示
                if(word.isShow==false){
                    word.isShow=true;
                }else{
                    word.isShow=false;
                }
            }else{//全部隐藏或展示
                let isShow = self.isShow;
                self.showData.forEach(function (item, index) {
                    if(!isShow){
                        item.isShow=true;
                    }else{
                        item.isShow=false;
                    }
                    var obj = document.getElementById("word_"+item.id);
                    obj.style.backgroundColor ="white";
                    word.progressBar = 0;

                });
                self.isShow=!self.isShow;
            }
            //控制统一展示按钮
            let findFlag ={};
            findFlag = self.showData.find((item)=>{
                return item.isShow==true;
            });
            self.isShow=findFlag!=undefined;

            var obj = document.getElementById("word_"+word.id);
            if(word.isShow){
                word['isPass'] = true;
                obj.classList.add('lined');
                obj.classList.remove('progress-1');
                self.continueBkAudio();//继续播放音乐
            }else{
                obj.classList.remove('lined');
            }
        },
        //点击往上滑动
        toTop(toIndex){
            let self = this;
            self.continueBkAudio();
            let findIndex = toIndex!=null?toIndex:-1;
            let line = 10;//跳到的行数
            if(self.isReview){
                line =self.pageSize;
                alert("复习模式不能使用!");
                return;
            }
            if(toIndex==null){
                self.showData.forEach(function (item, index) {
                    if(item.isShow){
                        findIndex= index;
                    }
                });
            }
            if(findIndex!=-1){
                document.documentElement.scrollTop = 0;
                //设置背景颜色
                var exit = true;
                self.showData.forEach(function (item, index) {
                    item['sortValue']=10;
                    var wordObj = document.getElementById("word_"+item.id);
                    wordObj.classList.remove('lined');

                    var obj = document.getElementById("tdId_"+item.id);
                    if(obj!=null){
                        obj.style.color ="#000";
                        item.progressBar = 0;
                        item['isEnd'] = false;//标记选中行的结束
                    }
                });
                self.showData.forEach(function (item, index) {
                    if(index> findIndex-line && index<=findIndex){
                    /*if(index<=findIndex){*/
                        if(exit){
                            document.documentElement.scrollTop = document.getElementById('word_'+item.id).offsetTop-30;
                            exit = false;
                        }
                        //设置div边框颜色
                        /*var divObj = document.getElementById("word_"+item.id);
                        divObj.style.borderLeft =index<=findIndex?"solid 1px #7c6e6e":"solid 0px #7c6e6e";*/
                        var tidObj = document.getElementById("tdId_"+item.id);
                        tidObj.style.color =index<=findIndex?"#d61d1d":"#7c6e6e";
                        item.isShow=false;
                        item['sortValue']= 10+ Math.random() + 0.5;
                    }
                    if(index>findIndex){
                        item['sortValue']=10000;
                    }
                    if(index==(findIndex+1)){
                        item['isEnd'] = true;//当前行结束
                    }
                });
                //乱序
                self.showData.sort(this.compare('sortValue'));
                self.progressBar(findIndex-line<=0?0:(findIndex-line+1));
            }
        },
        compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value1 - value2;  //降序只需要  return value2- value1
            }
        },
        musciDivSHow(){
            this.isShowMusicDiv = !this.isShowMusicDiv;
        },
        //播放声音
        playAudio(item){
            //url ='https:\\/\\/fanyiapp.cdn.bcebos.com\\/api\\/tts\\/95e906875b87d342d7325a36a4e1ab42.mp3';
            let self = this;
            if(this.sound){
                var audio = new Audio(item['uk-speech']);
                audio.play();
                audio.oncanplay = function () {//可以播放
                };
                audio.onended = function () {//播放结束
                    //console.log('播放结束'+self.musicAudio);
                    //self.musicAudio.volume=0.1;
                };
                audio.addEventListener('error', function () {
                    //发送到后台记录
                    /*var httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
                    httpRequest.open('GET', 'http://mytest.zicp.vip/hello/putWord?word='+item.word, true);
                    //httpRequest.send();//第三步：发送请求  将请求参数写在URL中
                    //alert('播放发生错误！');*/
                }, false);
            }
        },
        //开始背景音乐
        playBkAudio(item){
            var self = this;
            let value=null;
            if(self.musicAudio==null){
                self.musicAudio = new Audio(value==null?item.url:window.URL.createObjectURL(new Blob([value])));
            }
            self.musicAudio.pause();
            if(self.currMusicItem.url!=item.url){
                self.musicAudio =  new Audio(value==null?item.url:window.URL.createObjectURL(new Blob([value])));
            }
            // 当音频结束播放事件 播放下一首
            self.musicAudio.onended = function () {
                self.autoNextMusic();
            };
            self.musicAudio.volume = 0.1;
            self.currMusicItem = item;
            self.currMusicItem.status=1;
            self.musicAudio.play();
            self.updateMusicStatus();
        },
        //更新音乐状态
        updateMusicStatus(){
            var self =this;
            this.musicList.forEach(function (item, index) {
                if(self.currMusicItem.url == item.url){
                    item.status = 1;
                }else{
                    item.status = 0;
                }
            });
        },
        checkAudioUrl(){
            let self = this;
            englishData.forEach(function (item, index) {
                self.playAudio(item);
            });
        },
        //自动下一首
        autoNextMusic(){
            var self =this;
            var flagIndex = 0;
            this.musicList.forEach(function (item, index) {
                if(self.currMusicItem.url == item.url){
                    flagIndex =index+1;
                    return;
                }
            });
            if(flagIndex>=this.musicList.length){
                flagIndex=0;
            }
            this.playBkAudio(this.musicList[flagIndex]);
        },
        //每15s检查是否有背单词,如果没有则暂停背景音乐
        checkProgress(){
            let self =  this;
            setInterval(function () {
                var v = document.getElementsByClassName('progress-1');
                if(v.length==0){
                    //延迟执行
                    setTimeout(function () {
                        var v = document.getElementsByClassName('progress-1');
                        if(v.length==0){
                            self.pauseBkAudio();
                        }
                    }, 15000)
                }
            }, 30000);
        },
        //暂停背景音乐
        pauseBkAudio(){
            if(this.musicAudio!=null) {
                this.musicAudio.pause();
                this.currMusicItem.status = 2;
            }
        },
        //继续播放
        continueBkAudio(){
            if(this.musicAudio!=null){
                this.musicAudio.play();
                this.currMusicItem.status=1;
            }
        },
        soundBtn(){
            this.sound = !this.sound;
        },
        //数据分页
        returnAllPageFunc(currentPage,pageSize,arr) {
            var skipNum = (currentPage-1) * pageSize;
            var newArr = (skipNum + pageSize >= arr.length) ? arr.slice(skipNum, arr.length) : arr.slice(skipNum, skipNum + pageSize);
            if((skipNum + pageSize) >= arr.length){
                this.pageNum=currentPage;
            }
            return newArr;
        }},
}).mount('#app')